class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        int n = nums.size(), sum = 0, ret = 0;;
        unordered_map<int, int> hash(n); // 左存前缀和对k取模的余数，右存前缀和出现次数
        hash[0 % k] = 1;
        for(int i = 0; i < n; ++i)
        {
            sum += nums[i];
            int remainder = (sum % k + k) % k;
            if(hash[remainder] != 0)
            {
                ret += hash[remainder];
            }
            hash[remainder]++;
        }
        return ret;
    }
};